﻿/*-------------------------------------------------------------------------
* 命名空间: XrayDirection.ValueConverters/NotNullConverter
* 类       名: NotNullConverter
* 功      能:  TD
* 时      间:  2023/12/27 17:32:20
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using System;
using System.Collections;
using System.Globalization;
using System.Windows;
using System.Windows.Media.Converters;

namespace XrayDirection.ValueConverters
{
    /// <summary>
    /// 非空转换器(如果非空,返回true,否则返回false),并且如果目标控件类型是Visibility,转换为对应的Visibility格式
    /// </summary>
    public class NotNullConverter : OneWayConverter
    {
        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // 先根据value是否为null获取默认值
            bool res = value != null;
            switch (value)
            {
                case ICollection collection:
                    res = collection.Count > 0;
                    break;
                case string str:
                    res = !string.IsNullOrWhiteSpace(str);
                    break;
                case int i:
                    res = i != 0;
                    break;
                case double d:
                    res = Math.Abs(d) > 0.001;
                    break;
            }

            // 看看是否需要反转结果,根据parameter
            if ((parameter is bool inverse || parameter is string s && bool.TryParse(s, out inverse)) && inverse)
                res = !res;

            if (targetType == typeof(Visibility))
                return res ? Visibility.Visible : Visibility.Collapsed;

            return res;

        }
    }
}
